import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../layout/HomeView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView, 
      children:[
        {
          path:'/console',
          name:'console',
          meta:'主控台',
          component:()=>import('@/views/console/ConsoleView.vue')
        },
        {
          path:'/CommodityManagement',
          name:'CommodityManagement',
          meta:'商品管理',
          component:()=>import('@/views/CommodityManagement/CommodityManagement.vue')
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    }
  ]
})

// 导航守卫  
router.beforeEach((to, from, next) => {  
  const token = localStorage.getItem('user-token'); // 假设 token 存储在 localStorage 中  

  if (to.path !== '/login' && !token) {  
    // 如果尝试访问非登录页但没有 token，则重定向到登录页  
    next('/login');  
  }else if (to.path === '/' && token) {
    next('/console'); 
  } else {  
    // 其他情况，允许导航  
    next();  
  }  
});  

export default router
